package com.ff.miaosha;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class MutiThreadOrderExecutorDemo {

    private static ReentrantLock reentrantLock=new ReentrantLock();

    private static Condition c1=reentrantLock.newCondition();

    private static Condition c2=reentrantLock.newCondition();

    private static Condition c3=reentrantLock.newCondition();

    private static int num=1;

    private static final int COUNT=6;

    private volatile static boolean thread2IsStart=false;

    public static void main(String[] args) {
        new Thread1().start();
//        sleep(1000);
        new Thread2().start();
//        sleep(1000);
        new Thread3().start();
    }

    static class Thread1 extends Thread{
        @Override
        public void run() {
            try {
                while(true) {
                    reentrantLock.lock();
                    for (int i = 0; i < 5; i++) {
                        System.out.println("current 1 num:" + num);
                        sleep(1000);
                        num++;
                    }
                    reentrantLock.getHoldCount();
                    reentrantLock.getWaitQueueLength(c2);
                    c2.signal();
                    c1.await();
                    reentrantLock.unlock();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    static class Thread2 extends Thread{
        @Override
        public void run() {
            try {
                while (true){
                    reentrantLock.lock();
                    for (int i = 0; i < 5; i++) {
                        System.out.println("current 2 num:" + num);
                        sleep(1000);
                        num++;
                    }
                    thread2IsStart=true;
                    c3.signal();
                    c2.await();
                    reentrantLock.unlock();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    static class Thread3 extends Thread{
        @Override
        public void run() {
            try {
                while (true){
                    reentrantLock.lock();
                    if (!thread2IsStart)
                        c3.await();
                    for (int i = 0; i < 5; i++) {
                        System.out.println("current 3 num:" + num);
                        sleep(1000);
                        num++;
                    }
                    c1.signal();
                    c3.await();
                    reentrantLock.unlock();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
